<?php
/**
 * This file is part of Hyperf Mall.
 *
 * @link     https://gitee.com/scwlkj/hyperf_mall
 * @contact  hyperf_mall@163.com
 */

namespace App\Service;


use App\Common\Singleton;

abstract Class BaseService
{
    use Singleton;

    const SUCCESS_CODE = 200;
    const ERROR_CODE = 0;

    protected $service;

    public function __call(string $name, array $arguments)
    {
        $start_time = microtime(true);
        $args['saas_id'] =  '1001011';//get_saas_id();
        $args['access_token'] = 'xxxxxxxxxxxxxxx' ;//get_access_token() ;
        //$commonArgs['user_info'] = get_user_info();
       //$commonArgs['common_info'] = get_common_info();
        array_unshift($arguments, $args);
        array_unshift($arguments, $name);

        $result = retry(2, function () use ($name, $arguments, $start_time) {
            try {
                $ret = $this->service->initFunction($arguments);

                //$elapsed_time = microtime(true) - $start_time;

                if (empty($ret) || !isset($ret['code'])) {
                    throw new \Exception('接口调用失败');
                }

                if ($ret['code'] != self::SUCCESS_CODE) {
                    throw new \Exception($ret['msg'],$ret['code']);
                }

                return $ret['data'];
            } catch (\Throwable $exception) {
                /*$elapsed_time = microtime(true) - $start_time;
                debug_log(get_class($this) . "->{$name}", [
                    'arguments' => $arguments,
                    'exception' => $exception,
                    'trace' => $exception->getTraceAsString(),
                    'elapsed_time' => $elapsed_time,
                ]);*/
                throw $exception;
            }
        }, 200);

        debug_log(get_class($this) . "->{$name}", [
            'arguments' => $arguments,
            'result' => $result,
        ]);

        return $result;
    }
}
